package com.djl.seckilldemo.config;

import com.djl.seckilldemo.pojo.User;
import com.djl.seckilldemo.service.IUserService;
import com.djl.seckilldemo.util.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: seckill-demo
 * @description: 自定义用户参数
 * @author: Mr.dai
 * @create: 2021-10-18 18:04
 **/
@Component
public class UserArgumentResolvers implements HandlerMethodArgumentResolver {
    @Autowired
    IUserService userService;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return parameterType== User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String cooike = CookieUtil.getCookieValue(request, "ticket");
        if(StringUtils.isEmpty(cooike)){
            return  null;
        }
        return userService.getUserByCookie(cooike,request,response);
    }
}
